<template>
      <el-tree-select v-model="selectedCategoryId" :data="categoryData" :render-after-expand="false"
        :default-expand-all="true"  :check-strictly="true" @change="change" />
</template>
<script setup lang="ts">
import { ref, onMounted,watch } from "vue";
import { categoryApi } from '@/api'
//数据流向是单向的， 从父到子
const props = defineProps({ 
    modelValue: { type: Number, default: 0 } , 
    rootName: { type: String, default: '一级分类'} 
})

const emit = defineEmits(['update:modelValue']) // 触发器，声明。提前给老爹声明一下，我待会可能用动用你的money
const selectedCategoryId = ref(0)
const categoryData = ref([])
onMounted(() => {

    callCategoryApi()
})
watch(()=>props.modelValue,(newVal:any,oldVal:any)=>{

    selectedCategoryId.value = newVal
})
const change = (val:number)=>{
    emit("update:modelValue",val)
    selectedCategoryId.value = val
}
const callCategoryApi = () => {
  categoryApi.select.call().then((categoryDataRes: any) => {
    categoryDataRes.forEach((item:any) => {
      item.value = item.id
      item.label = item.name
    });
    let categoryData2 = categoryDataRes.reduce((duzi: any, currentValue: any) => {

      currentValue.children = categoryDataRes.filter((item: any) => item.parentId === currentValue.id)
      if (currentValue.parentId === 0) {
        duzi.push(currentValue)
      }
      return duzi
    }, [])


    categoryData.value = [{value: 0,label:props.rootName, }].concat(categoryData2)
  })
}
</script>